import {defineConfig,loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
// 自动导入composition api 和 生成全局typescript说明
import AutoImport from 'unplugin-auto-import/vite'
// 自动按需导入组件和注册组件
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import * as path from 'path'

import {viteMockServe} from 'vite-plugin-mock'
import autoprefixer from 'autoprefixer'
import postCssPxToRem from 'postcss-pxtorem'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd());
  console.log('*********************')
  console.log('mode', mode)
  console.log('env', env)

  return {
    base: env.VITE_PUBLIC_PATH,
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: "true",
    },
    plugins: [
      vue(),
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            axios: [
              ['default', 'axios']
            ]
          }
        ],
        // 解析器，例如element-plus的ElementPlusResolver
        resolvers: [ElementPlusResolver()],
        eslintrc: {
          enabled: true, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        dts: true // 根目录自动生成auto-import.d.ts  "src/auto-import.d.ts"  生成 `auto-import.d.ts` 全局声明
      }),
      viteMockServe({
        logger: true,
        watchFiles: true, // 监视文件更改
        mockPath: 'mock', // 解析根目录下的mock文件夹
        supportTs: true, // 打开后，可以读取 ts 文件模块。
        localEnabled: true,
        prodEnabled: true // 生产打包开关
      }),
      Components({
        resolvers: [ElementPlusResolver()] // ElementPlus按需加载
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
      resolve: {
    // src目录别名
    alias: {
      '@': path.join(__dirname, './src')
    }
  },
    css: {
      postcss: {
        plugins: [
          autoprefixer,
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: atRule => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
          // 移除postCssPxToRem配置
        ],
      },
      preprocessorOptions: {
        // css 全局变量
        scss: {
          additionalData: '@import "@/styles/variables.scss";'
        }
      }
    },
    // 代理
    server: {
      port: 8080,
        // 设置开发环境proxy代理
        proxy: {
        '/api': {
          target: 'http://192.168.1.20/zhpjapi',
            changeOrigin: true,
            rewrite: path => path.replace(/^\/api/, ''), // 路径不变，直接转发

            // 添加以下配置以处理CORS
            configure: (proxy, options) => {
              proxy.on('proxyRes', (proxyRes, req, res) => {
                // 移除重复的Access-Control-Allow-Origin头
                if (proxyRes.headers['access-control-allow-origin']) {
                  delete proxyRes.headers['access-control-allow-origin'];
                }
                // 设置单一的Access-Control-Allow-Origin头
                proxyRes.headers['access-control-allow-origin'] = '*';
              });
            }
        },
      }
    },
  }
})
